package com.lagou.stickpack;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 服务端自定义拦截器
 */
public class NettyServerHandler implements ChannelInboundHandler {

    private int count = 0;

    /**
     * 通道读取事件
     *
     * @param channelHandlerContext 通道上下文对象
     * @param o                     消息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        //粘包演示
        ByteBuf byteBuf = (ByteBuf) o;
        System.out.println("客户端发来的消息: " + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("读取的次数: " + ++count + "次");
    }

    /**
     * 读取完毕事件
     *
     * @param channelHandlerContext 通道上下文对象
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext channelHandlerContext) throws Exception {
        System.out.println("数据读取完成, 给客户端响应信息========");
        ByteBuf byteBuf = Unpooled.copiedBuffer("你好客户端,我是服务端", CharsetUtil.UTF_8);
        channelHandlerContext.writeAndFlush(byteBuf);
    }

    /**
     * 异常发生事件
     *
     * @param channelHandlerContext 通道上下文对象
     * @param throwable             异常
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
        System.out.println("发生了异常========");
        throwable.printStackTrace();
        channelHandlerContext.close();
    }


    @Override
    public void channelRegistered(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void channelInactive(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void handlerAdded(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext channelHandlerContext) throws Exception {

    }

}
